﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;

using System.IO;

namespace Includes
{
   /// <summary>
   /// HCS project specific wrapper for the GSMcom library
   /// </summary>
   public static class GSMComWrapper
   {
      // Current Connection
      private static GsmCommMain activeConnection;

      /// <summary>
      /// Establishes a connection to the GSM modem
      /// </summary>
      /// <param name="comPort"> Com port the modem is connected to </param>
      /// <param name="baudRate"> Baud rate to use for the serial connection </param>
      /// <param name="timeOut"> ms to timeout </param>
      /// <returns> true if connection could be established </returns>
      public static bool init(int comPort, int baudRate, int timeOut)
      {
         try
         {
            activeConnection = new GsmCommMain(comPort,baudRate,timeOut);
            activeConnection.Open();
         }
         catch(Exception)
         {
            return false;
         }
         return true;
      }    
      
      /// <summary>
      /// Sends an SMS to destination number
      /// </summary>
      /// <param name="sms"> Sms to send </param>
      /// <returns> true if SMS was sent sucessfully, false otherwise </returns>
      public static bool sendSMS(SMS sms)
      {
         try
         {
            // Send an SMS message
            SmsSubmitPdu pdu;

            // Send message in the default format
            pdu = new SmsSubmitPdu(sms.text, sms.receipientNumber);
            pdu.ReplyPathExists = false;
            
            // Request immediate display (alert)
            pdu.DataCodingScheme |= (byte)DataCodingScheme.GeneralCoding.Class0;

            activeConnection.SendMessage(pdu);
         }
         catch (Exception)
         {
            return false;
         }

         return true;
      }

      /// <summary>
      /// Receives all pending SMS from the GSM modem
      /// </summary>
      /// <returns> All pending SMS </returns>
      public static SMS[] receiveSMSes()
      {
         List<SMS> resultSMSes= new List<SMS>(5);

         try
         {
            // Drop useless SMSes
            DecodedShortMessage[] allMessages = activeConnection.ReadMessages(PhoneMessageStatus.All, PhoneStorageType.Phone);

            foreach (DecodedShortMessage message in allMessages)
            {
               if (!(message.Data is SmsDeliverPdu))
               {
                  // Messages that are not received must be deleted immediately
                  Console.Write("{0} : {1} : {2} DROPPED\n", message.Index, "<not relevant>", message.Data.UserDataText);
                  activeConnection.DeleteMessage(message.Index, PhoneStorageType.Phone);
               }
            }


            // Read SMSes
            DecodedShortMessage[] relevantMessages = activeConnection.ReadMessages(PhoneMessageStatus.All, PhoneStorageType.Phone);

            if (relevantMessages.Length < 1)
               throw new Exception("No sms received");

            //else
            Console.Write("\n{0} SMS pending\n", relevantMessages.Length);

            // Display pending messages
            SMS tmp = new SMS();
            Console.Write("Returning:\n---------------\n");
            foreach (DecodedShortMessage message in relevantMessages)
            {
               tmp = new SMS();
               tmp.senderNumber  = ((SmsDeliverPdu)message.Data).OriginatingAddress;
               tmp.text          = ((SmsDeliverPdu)message.Data).UserDataText;
               tmp.ID            = message.Index;
               Console.Write("{0} : {1} : {2}\n", tmp.ID, tmp.senderNumber, tmp.text);

               resultSMSes.Add(tmp);
            }
         }
         catch (Exception)
         {
            throw new Exception("Receiving or decoding SMS failed");
         }
         return resultSMSes.ToArray();
      }

      /// <summary>
      /// Deletes the SMS that is stored at position ID
      /// </summary>
      /// <param name="ID"> ID of the SMS to delete </param>
      public static void deleteSMSbyId(int ID)
      {
         activeConnection.DeleteMessage(ID, PhoneStorageType.Phone);
      } 
   }
}
